const config = require('./config')
const initData = require('./app/init-data')

class AppBootHook {
  constructor(app) {
    this.app = app
  }

  configWillLoad() {
    // Ready to call configDidLoad,
    // Config, plugin files are referred,
    // this is the last chance to modify the config.

    const { config } = this.app
  }

  // 配置加载完成
  configDidLoad() {
    const mongoose = this.app.mongoose

    require('mongoose-long')(mongoose)

    // mongoose.set('returnOriginal', false);

    mongoose.set('toJSON', { virtuals: true, getters: true })
    // mongoose.set('toObject', { virtuals: true, getters: true });
    mongoose.set('debug', (collectionName, methodName, query, doc) => {
      if (collectionName.indexOf('request_log') != -1) return
      console.log(`Mongoose: ${collectionName}.${methodName}`, JSON.stringify(query), doc)
    })
    ;['host', 'uploadDir'].map((key) => {
      config[key] = this.app.config[key]
    })
  }

  // 所有的配置已经加载完毕
  // 可以用来加载应用自定义的文件，启动自定义的服务
  async didLoad() {
    // All files have loaded, start plugin here.

    this.initDatabase()
  }

  // 所有的插件都已启动完毕，但是应用整体还未 ready
  // 可以做一些数据初始化等操作，这些操作成功才会启动应用
  async willReady() {
    // All plugins have started, can do some thing before app ready
  }

  // 应用已经启动完毕
  async didReady() {
    // Worker is ready, can do some things
    // don't need to block the app boot.
    // require('./app/test/juhe-express')(this);
  }

  // http / https server 已启动，开始接受外部请求
  // 此时可以从 app.server 拿到 server 的实例
  async serverDidReady() {
    // Server is listening.
  }

  async beforeClose() {
    // Do some thing before app close.
  }

  // 初始化数据库
  async initDatabase() {
    const { config } = this.app

    console.log('[App] 环境', config.env)
    console.log('[App] 数据库', config.dbName)

    if (config.env == 'local') initData(this.app)
  }
}

module.exports = AppBootHook
